﻿using System;
using System.Collections.Generic;
using StockTrader.Platform.Logging;
using StockTrader.Stocks.General;
using StockTrader.Utilities;
using System.Globalization;
using System.IO;
using StockTrader.API.TradingAlgos;
using StockTrader.Common;

namespace StockTrader.Stocks.Utilities.Broker
{
    public partial class AlgoRunUtils
    {
        public static event ResetChartHandler EventResetChart;

        // EOD algo
        public static void RunExperimentsOnAlgo_EODfileGenerator(object obj)
        {
            BrokerAccountObject brokerAccountObj = (BrokerAccountObject)obj;
            IBroker broker = brokerAccountObj.broker;

            AlgoData1 algoData = (AlgoData1)brokerAccountObj.CustomData;

            List<DerivativeQuoteInformation> dqis = new List<DerivativeQuoteInformation>(5000);

            AddTickChartDelegate dataDelegate = algoData.DataDelegate;

            //var chartDelegate = (Action<ChartTickPoint>)brokerAccountObj.CustomData2;

            var chartDelegate = algoData.ChartDelegate;

            // Stock dir and symbol
            //string stockDaysDir = @"E:\StockData\10-Year-EOD-Data\";

            //string[] matchingDirs = Directory.GetDirectories(stockDaysDir, "200905*");//, SearchOption.AllDirectories);

            //IEnumerable<string> allTickFiles = Directory.EnumerateFiles(stockDaysDir);

            string[] symbols = algoData.Symbol.Split(';');
            //string symbol = algoData.Symbol;


            // Go for each symbol
            foreach (string symbol in symbols)
            {
                string tickFileName = @"E:\StockData\10-Year-EOD-Data-MyFormat\" + symbol + "-EOD.txt";

                string tickFile = @"E:\StockData\10-Year-EOD-Data-Original\" + symbol + ".csv";

                //symbol = symbol.Substring(0, symbol.Length - ".csv".Length);

                // Set the tracing filename
                string traceFileNamePart = DateTime.Today.ToString("yyyyMMdd") + "-" + Guid.NewGuid().ToString();
                string traceFileName = symbol + "-EOD-" + traceFileNamePart;
                //string warningsTraceFileName = symbol + "-Warnings-" + traceFileNamePart;
                //FileTracing.SetTraceFilename(traceFileName);

                dqis.Clear();


                //string tickFile = Path.Combine(stockDaysDir, symbolFile);

                if (!File.Exists(tickFile))
                {
                    Logger.LogWarningMessage(string.Format("TickFile {0} not found.", tickFile));
                    continue;
                }

                //FileInfo fi = new FileInfo(tickFile);
                //long fileSize = fi.Length;

                //if (fileSize < 1024 * 2)
                //{
                //    Logger.LogWarningMessage(string.Format("TickFile {0} is less than 2KB.", tickFile));
                //    continue;
                //}

                // Read 1 file
                using (FileStream fs = new FileStream(tickFile, FileMode.Open, FileAccess.Read))
                {
                    using (StreamReader sr = new StreamReader(fs))
                    {
                        string s = null;
                        // discard first tick as it is opening line with Column names
                        s = sr.ReadLine();

                        do
                        {
                            s = sr.ReadLine();

                            DerivativeQuoteInformation dqi = ParseTickString(s, TickFormatType.EOD);

                            // Add to list of DQI 
                            if (dqi != null)
                            {
                                // Add only stablemarket ticks, i.e. after inital 5 minutes. Start from 10 AM for stable data
                                //if (MarketUtils.IsTimeAfter10AM(dqi.UpdateTime))
                                {
                                    dqis.Add(dqi);
                                }
                            }

                            //if (dqis.Count > 10000)
                            //    break;


                        } while (s != null);
                    }
                }

                // Reverse the dqis list since, the EOD data is given in reverse order
                dqis.Reverse();

                DerivativeQuoteInformation prevdqi = dqis[0];
                double ltp = dqis.Count > 0 ? dqis[0].LastTradedPriceDouble : 0;
                double lcp = dqis.Count > 0 ? dqis[0].OfferPriceDouble : 0;
                double adjFactor = 1;
                int count = 0;
                // Purify the EOD data (adjustment for bonus/splits etc)
                foreach (DerivativeQuoteInformation dqi in dqis)
                {
                    ltp = ltp == 0 ? 1 : ltp;
                    lcp = lcp == 0 ? 1 : lcp;
                    double priceDiffPerc = Math.Abs(dqi.LastTradedPriceDouble - ltp) / ltp;
                    count++;

                    if (priceDiffPerc > 0.25)
                    {
                        // Here offerPrice field is used to hold day adjusted close price
                        double confirmPriceDiffPerc = Math.Abs(dqi.LastTradedPriceDouble - lcp) / lcp;

                        if (confirmPriceDiffPerc > 0.25 && count > 5)
                        {
                            double newAdjFactor = dqi.LastTradedPriceDouble / ltp;
                            adjFactor *= newAdjFactor;
                            Logger.LogWarningMessage(string.Format("Price Adjustment: Symbol={2}, Date={0}, Factor={1}", dqi.UpdateTime, newAdjFactor, symbol));
                        }
                    }

                    ltp = dqi.LastTradedPriceDouble;
                    lcp = dqi.OfferPriceDouble;

                    dqi.LastTradedPriceDouble *= adjFactor;
                }

                //if (!File.Exists(tickFileName))
                {
                    using (FileStream fs = new FileStream(tickFileName, FileMode.Create, FileAccess.Write))
                    {
                        using (StreamWriter sw = new StreamWriter(fs))
                        {
                            foreach (DerivativeQuoteInformation dqi in dqis)
                            {
                                string str = dqi.UpdateTime.ToString("yyyyMMdd:HH:mm:ss") + "," + dqi.LastTradedPriceDouble;
                                sw.WriteLine(str);
                            }
                        }
                    }
                }

                Logger.FlushTraces();

                continue;


                double percChangeForMarketDirectionChange = 1;

                do
                {
                    Logger.LogInformationalMessage("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
                    Logger.LogInformationalMessage("~~~~~~~~~~~~~~~~~~~~~ percChangeForMarketDirectionChange = " + percChangeForMarketDirectionChange +
                        "~~~~~~~~~~~~~~~~~~~~~~~~~~");
                    Logger.LogInformationalMessage("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");

                    bool doBreak = false;
                    Algo10_MultipleLotBuySellAnalyzer algo = new Algo10_MultipleLotBuySellAnalyzer(
                                        dataDelegate,
                                        chartDelegate,
                                        true,//mkdConfig.mock,
                                        true,//mkdConfig.bIsReplayMode,
                        //@"D:\StockData\NIFTY_ticks.txt",//mkdConfig.replayTickFile,
                        //@"D:\StockData\NIFTY-5Oct2005-16May2007-100000ticks.txt",
                                        @"D:\StockData\NIFTY-5Oct2005-7Apr2006-10000ticks.txt",
                                         @"D:\StockData\NIFTY_positions1.txt",//mkdConfig.positionsFile,

                                        false,//mkdConfig.useProbableTradeValue,
                                        false, // isMarketClosingSquareOff
                                        false, // isSquareOffTriggerEnabled
                                        false, // isMinProfitMustEnabled
                                        percChangeForMarketDirectionChange,//mkdConfig.percChangeForMarketDirectionChange,
                                        percChangeForMarketDirectionChange,//mkdConfig.percChangeThresholdForSquareOff,
                        //mkdConfig.percentageChangeForFreshBuy,
                        //mkdConfig.percentageChangeForShortSquareOff,
                        //mkdConfig.percentageChangeForFreshShort,
                        //mkdConfig.percentageChangeForLongSquareOff,

                                        100,//mkdConfig.stopLossPerc, //stop loss percentage
                                        0.1,//mkdConfig.minProfitPerc, //minimum profit percentage


                                        true,//mkdConfig.allowShort, //Short Sell Allowed
                                        true,//mkdConfig.allowLong, //Long Position Allowed

                                        null,  // pending open positions or inital orders

                                        broker,
                                        symbol,//stockCode,
                                        50,//quantity,
                                        InstrumentType.FutureIndex,//instrType,
                                        MarketUtils.GetExpiryExactDate(new DateTime(2011, 4, 28)),//mkdConfig.expiryDate,
                        //mkdConfig.stockCode,
                        //mkdConfig.quantity,
                        //mkdConfig.instType,
                        //mkdConfig.expiryDate//,

                                        1,//mkdConfig.maxTotalPositions,
                                        1,//mkdConfig.maxLongPositions,
                                        1,//mkdConfig.maxShortPositions,

                                        7000,//mkdConfig.longCeilingPrice,
                                        1000,//mkdConfig.shortFloorPrice,
                                        0.2,//mkdConfig.positionSpacingPerc,
                                        0.04//mkdConfig.brokerage

                                    );

                    algo.Prolog();
                    //algo.RunCoreAlgo();
                    // Run for each quote tick now out of all collected from the replay file
                    foreach (DerivativeQuoteInformation dqi in dqis)
                    {
                        if (doBreak)
                            break;


                        algo.mTotalTickCount++;

                        //Thread.Sleep(100);

                        try
                        {
                            algo.AddTick(dqi, true, null);
                        }
                        catch
                        {
                            FileTracing.TraceOut("Exception in algo.AddTick()");
                        }

                        algo.ltp = dqi.LastTradedPriceDouble;
                    }

                    algo.Epilog();

                    percChangeForMarketDirectionChange += 1;

                    EventResetChart(null, null);

                    foreach (DerivativeQuoteInformation dqi in dqis)
                    {
                        dqi.UpdateTime = dqi.OriginalTime;
                    }

                } while (percChangeForMarketDirectionChange <= 10);

            } //foreach symbol


        }

        // IEOD algo
        public static void RunExperimentsOnAlgo_IEODfileGenerator(object obj)
        {
            BrokerAccountObject brokerAccountObj = (BrokerAccountObject)obj;
            IBroker broker = brokerAccountObj.broker;

            AlgoData1 algoData = (AlgoData1)brokerAccountObj.CustomData;

            List<DerivativeQuoteInformation> dqis = new List<DerivativeQuoteInformation>(100000);

            AddTickChartDelegate dataDelegate = algoData.DataDelegate;

            //var chartDelegate = (Action<ChartTickPoint>)brokerAccountObj.CustomData2;

            var chartDelegate = algoData.ChartDelegate;

            // Stock dir and symbol
            string stockDaysDir = @"E:\StockData\6month-IEOD-Data-Original\";

            //string[] matchingDirs = Directory.GetDirectories(stockDaysDir, "200905*");//, SearchOption.AllDirectories);

            string[] matchingDirs = Directory.GetDirectories(stockDaysDir, "*");

            string[] symbols = algoData.Symbol.Split(';');
            //string symbol = algoData.Symbol;

            // Go for each symbol
            foreach (string symbol in symbols)
            {
                string tickFileName = @"E:\StockData\6month-IEOD-Data-MyFormat\" + symbol + "-IEOD.txt";

                // If the consolidated data file is already contructed then just move on to next symbol
                if (File.Exists(tickFileName) && File.GetLastWriteTime(tickFileName) > DateTime.Now.AddDays(-3))
                {
                    continue;
                }


                string symbolFile = symbol + ".csv";

                // Set the tracing filename
                string traceFileNamePart = DateTime.Today.ToString("yyyyMMdd") + "-IEOD-" + Guid.NewGuid().ToString();
                string traceFileName = symbol + "-" + traceFileNamePart;
                //string warningsTraceFileName = symbol + "-Warnings-" + traceFileNamePart;
                FileTracing.SetTraceFilename(traceFileName);

                dqis.Clear();

                // Go through Each day's data for given symbol
                foreach (string dir in matchingDirs)
                {
                    string tickFile = Path.Combine(dir, symbolFile);

                    if (!File.Exists(tickFile))
                    {
                        Logger.LogWarningMessage(string.Format("TickFile {0} not found.", tickFile));
                        continue;
                    }

                    //FileInfo fi = new FileInfo(tickFile);
                    //long fileSize = fi.Length;

                    //if (fileSize < 1024 * 2)
                    //{
                    //    Logger.LogWarningMessage(string.Format("TickFile {0} is less than 2KB.", tickFile));
                    //    continue;
                    //}

                    // Read 1 file
                    using (FileStream fs = new FileStream(tickFile, FileMode.Open, FileAccess.Read))
                    {
                        using (StreamReader sr = new StreamReader(fs))
                        {
                            string s = null;
                            // discard first tick as it is opening (Skewed) tick and very different from the subsequent tick.
                            s = sr.ReadLine();

                            do
                            {
                                s = sr.ReadLine();

                                DerivativeQuoteInformation dqi = ParseTickString(s, TickFormatType.IEOD);

                                // Add to list of DQI 
                                if (dqi != null)
                                {
                                    // Add only stablemarket ticks, i.e. after inital 5 minutes. Start from 10 AM for stable data
                                    //if (MarketUtils.IsTimeAfter10AM(dqi.UpdateTime))
                                    {
                                        dqis.Add(dqi);
                                    }
                                }

                                //if (dqis.Count > 10000)
                                //    break;


                            } while (s != null);
                        }
                    }
                } // all matchingdirs for all days data collected


                // Optionally write this data to a single file
                // Write to tickfile

                //tickFileName = @"E:\StockData\6month-IEOD-Data-MyFormat\" + symbol + "-IEOD.txt";

                //if (!File.Exists(tickFileName))
                {
                    using (FileStream fs = new FileStream(tickFileName, FileMode.Create, FileAccess.Write))
                    {
                        using (StreamWriter sw = new StreamWriter(fs))
                        {
                            foreach (DerivativeQuoteInformation dqi in dqis)
                            {
                                string str = dqi.UpdateTime.ToString("yyyyMMdd:HH:mm:ss") + "," + dqi.LastTradedPriceDouble;
                                sw.WriteLine(str);
                            }
                        }
                    }
                }

                continue; //dummy just to first collate all tickfiles for each symbol into single file for that symbol

                double percChangeForMarketDirectionChange = 0.1;

                do
                {
                    Logger.LogInformationalMessage("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
                    Logger.LogInformationalMessage("~~~~~~~~~~~~~~~~~~~~~ percChangeForMarketDirectionChange = " + percChangeForMarketDirectionChange +
                        "~~~~~~~~~~~~~~~~~~~~~~~~~~");
                    Logger.LogInformationalMessage("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");

                    bool doBreak = false;
                    Algo1 algo = new Algo1(
                                        dataDelegate,
                                        chartDelegate,
                                        true,//mkdConfig.mock,
                                        true,//mkdConfig.bIsReplayMode,
                        //@"D:\StockData\NIFTY_ticks.txt",//mkdConfig.replayTickFile,
                        //@"D:\StockData\NIFTY-5Oct2005-16May2007-100000ticks.txt",
                                        @"D:\StockData\NIFTY-5Oct2005-7Apr2006-10000ticks.txt",
                                         @"D:\StockData\NIFTY_positions1.txt",//mkdConfig.positionsFile,
                                         9,
                                        false,//mkdConfig.useProbableTradeValue,
                                        true, // isMarketClosingSquareOff
                                        false, // isSquareOffTriggerEnabled
                                        false, // isMinProfitMustEnabled
                                        percChangeForMarketDirectionChange,//mkdConfig.percChangeForMarketDirectionChange,
                                        percChangeForMarketDirectionChange,//mkdConfig.percChangeThresholdForSquareOff,
                        //mkdConfig.percentageChangeForFreshBuy,
                        //mkdConfig.percentageChangeForShortSquareOff,
                        //mkdConfig.percentageChangeForFreshShort,
                        //mkdConfig.percentageChangeForLongSquareOff,

                                        100,//mkdConfig.stopLossPerc, //stop loss percentage
                                        0.1,//mkdConfig.minProfitPerc, //minimum profit percentage


                                        true,//mkdConfig.allowShort, //Short Sell Allowed
                                        true,//mkdConfig.allowLong, //Long Position Allowed

                                        null,  // pending open positions or inital orders

                                        broker,
                                        symbol,//stockCode,
                                        50,//quantity,
                                        InstrumentType.FutureIndex,//instrType,
                                        MarketUtils.GetExpiryExactDate(new DateTime(2011, 4, 28)),//mkdConfig.expiryDate,
                        //mkdConfig.stockCode,
                        //mkdConfig.quantity,
                        //mkdConfig.instType,
                        //mkdConfig.expiryDate//,

                                        1,//mkdConfig.maxTotalPositions,
                                        1,//mkdConfig.maxLongPositions,
                                        1,//mkdConfig.maxShortPositions,

                                        7000,//mkdConfig.longCeilingPrice,
                                        1000,//mkdConfig.shortFloorPrice,
                                        0.2,//mkdConfig.positionSpacingPerc,
                                        0.04//mkdConfig.brokerage

                                    );

                    algo.Prolog();
                    //algo.RunCoreAlgo();
                    // Run for each quote tick now out of all collected from the replay file
                    foreach (DerivativeQuoteInformation dqi in dqis)
                    {
                        if (doBreak)
                            break;

                        if (!MarketUtils.IsTimeAfter10AM(dqi.UpdateTime))
                        {
                            continue;
                        }

                        algo.mTotalTickCount++;

                        //Thread.Sleep(100);

                        try
                        {
                            algo.AddTick(dqi, true, null);
                        }
                        catch
                        {
                            FileTracing.TraceOut("Exception in algo.AddTick()");
                        }

                        algo.ltp = dqi.LastTradedPriceDouble;
                    }

                    algo.Epilog();

                    percChangeForMarketDirectionChange += 0.2;

                    EventResetChart(null, null);

                    foreach (DerivativeQuoteInformation dqi in dqis)
                    {
                        dqi.UpdateTime = dqi.OriginalTime;
                    }

                } while (percChangeForMarketDirectionChange <= 2.5);

            } //foreach symbol
        }

        public static void RunExperimentsOnAlgo(object obj)
        {
            BrokerAccountObject brokerAccountObj = (BrokerAccountObject)obj;
            IBroker broker = brokerAccountObj.broker;

            AlgoData algoData = (AlgoData)brokerAccountObj.CustomData;

            string mReplayTickFile = algoData.TickFile;

            AddTickChartDelegate dataDelegate = algoData.DataDelegate;

            //var chartDelegate = (Action<ChartTickPoint>)brokerAccountObj.CustomData2;

            var chartDelegate = algoData.ChartDelegate;

            List<DerivativeQuoteInformation> dqis = new List<DerivativeQuoteInformation>(100000);

            using (FileStream fs = new FileStream(mReplayTickFile, FileMode.Open, FileAccess.Read))
            {
                using (StreamReader sr = new StreamReader(fs))
                {
                    string s = null;
                    do
                    {
                        s = sr.ReadLine();
                        if (s != null)
                        {
                            string[] parts = s.Split(';');

                            IFormatProvider culture = new CultureInfo("en-US", true);
                            DateTime dt = DateTime.ParseExact(parts[0], "yyyyMMdd:HH:mm:ss", culture);
                            int volumeTraded = 0;
                            if (parts.Length == 7)
                            {
                                volumeTraded = int.Parse(parts[6]);
                            }

                            DerivativeQuoteInformation dqi = new DerivativeQuoteInformation(
                                dt,
                                double.Parse(parts[1]),
                                double.Parse(parts[2]),
                                double.Parse(parts[3]),
                                int.Parse(parts[4]),
                                int.Parse(parts[5]),
                                volumeTraded
                                );

                            // Add to list of DQI 
                            dqis.Add(dqi);

                            //if (dqis.Count > 10000)
                            //    break;
                        }

                    } while (s != null);
                }
            }

            double percChangeForMarketDirectionChange = 0.1;

            do
            {
                bool doBreak = false;
                Algo7_MultipleLotBuySellAnalyzer algo = new Algo7_MultipleLotBuySellAnalyzer(
                                    dataDelegate,
                                    chartDelegate,
                                    true,//mkdConfig.mock,
                                    true,//mkdConfig.bIsReplayMode,
                    //@"D:\StockData\NIFTY_ticks.txt",//mkdConfig.replayTickFile,
                    //@"D:\StockData\NIFTY-5Oct2005-16May2007-100000ticks.txt",
                                    @"D:\StockData\NIFTY-5Oct2005-7Apr2006-10000ticks.txt",
                                     @"D:\StockData\NIFTY_positions1.txt",//mkdConfig.positionsFile,

                                    false,//mkdConfig.useProbableTradeValue,
                                    false, // isMarketClosingSquareOff
                                    false, // isSquareOffTriggerEnabled
                                    false, // isMinProfitMustEnabled
                                    percChangeForMarketDirectionChange,//mkdConfig.percChangeForMarketDirectionChange,
                                    percChangeForMarketDirectionChange,//mkdConfig.percChangeThresholdForSquareOff,
                    //mkdConfig.percentageChangeForFreshBuy,
                    //mkdConfig.percentageChangeForShortSquareOff,
                    //mkdConfig.percentageChangeForFreshShort,
                    //mkdConfig.percentageChangeForLongSquareOff,

                                    100,//mkdConfig.stopLossPerc, //stop loss percentage
                                    0.1,//mkdConfig.minProfitPerc, //minimum profit percentage


                                    true,//mkdConfig.allowShort, //Short Sell Allowed
                                    true,//mkdConfig.allowLong, //Long Position Allowed

                                    null,  // pending open positions or inital orders

                                    broker,
                                    "NIFTY",//stockCode,
                                    50,//quantity,
                                    InstrumentType.FutureIndex,//instrType,
                                    MarketUtils.GetExpiryExactDate(new DateTime(2011, 4, 28)),//mkdConfig.expiryDate,
                    //mkdConfig.stockCode,
                    //mkdConfig.quantity,
                    //mkdConfig.instType,
                    //mkdConfig.expiryDate//,

                                    1,//mkdConfig.maxTotalPositions,
                                    1,//mkdConfig.maxLongPositions,
                                    1,//mkdConfig.maxShortPositions,

                                    7000,//mkdConfig.longCeilingPrice,
                                    1000,//mkdConfig.shortFloorPrice,
                                    0.2,//mkdConfig.positionSpacingPerc,
                                    0.04//mkdConfig.brokerage

                                );

                algo.Prolog();
                //algo.RunCoreAlgo();
                // Run for each quote tick now out of all collected from the replay file
                foreach (DerivativeQuoteInformation dqi in dqis)
                {
                    if (doBreak)
                        break;


                    algo.mTotalTickCount++;

                    //Thread.Sleep(100);

                    try
                    {
                        algo.AddTick(dqi, true, null);
                    }
                    catch
                    {
                        FileTracing.TraceOut("Exception in algo.AddTick()");
                    }

                    algo.ltp = dqi.LastTradedPriceDouble;
                }

                algo.Epilog();

                percChangeForMarketDirectionChange += 0.1;

                EventResetChart(null, null);

                foreach (DerivativeQuoteInformation dqi in dqis)
                {
                    dqi.UpdateTime = dqi.OriginalTime;
                }

            } while (percChangeForMarketDirectionChange <= 2.2);
        }

        public static DerivativeQuoteInformation ParseTickString(string s, TickFormatType tickFormat)
        {
            if (string.IsNullOrEmpty(s))
                return null;

            DerivativeQuoteInformation dqi = null;

            try
            {
                if (tickFormat == TickFormatType.IEOD)
                {
                    //ABB,20091007,09:55:07,786.10,786.10,786.10,786.10,0,0
                    string[] parts = s.Split(',');

                    IFormatProvider culture = new CultureInfo("en-US", true);
                    string dateString = parts[1] + ":" + parts[2];
                    DateTime dt = DateTime.ParseExact(dateString, "yyyyMMdd:HH:mm:ss", culture);

                    //string tempStr = parts[1].Insert(4, "-").Insert(7, "-");
                    //DateTime lastTradeTime = DateTime.Parse(tempStr);
                    //tempStr = parts[2];

                    //lastTradeTime += TimeSpan.Parse(tempStr);

                    double ltp = double.Parse(parts[3]);
                    //double bid = double.Parse(parts[4]);
                    //double offer = double.Parse(parts[5]);

                    // default 1000 offer and bid qty and volume traded as 0

                    //dqi = new DerivativeQuoteInformation(dt, ltp, bid, offer, 1000, 1000, 0);

                    dqi = new DerivativeQuoteInformation(dt, ltp, ltp, ltp, 1000, 1000, 0);


                }
                else if (tickFormat == TickFormatType.Custom)
                {
                    //20090910:10:40:59;273.4;273.3;273.45;2500;2500;0
                    string[] parts = s.Split(';');

                    IFormatProvider culture = new CultureInfo("en-US", true);
                    DateTime dt = DateTime.ParseExact(parts[0], "yyyyMMdd:HH:mm:ss", culture);
                    int volumeTraded = 0;
                    if (parts.Length == 7)
                    {
                        volumeTraded = int.Parse(parts[6]);
                    }

                    dqi = new DerivativeQuoteInformation(
                        dt,
                        double.Parse(parts[1]),
                        double.Parse(parts[2]),
                        double.Parse(parts[3]),
                        int.Parse(parts[4]),
                        int.Parse(parts[5]),
                        volumeTraded
                        );
                }
                else if (tickFormat == TickFormatType.EOD)
                {
                    // Date,Open,High,Low,Close,Volume,Adj Close
                    // 2011-04-13,675.00,694.30,665.75,687.75,743800,687.75

                    try
                    {
                        string[] parts = s.Split(',');

                        IFormatProvider culture = new CultureInfo("en-US", true);
                        DateTime dt = DateTime.ParseExact(parts[0], "yyyy-MM-dd", culture);

                        double ltp = double.Parse(parts[1]); // Some close prices are incorrect in EOD data files, so consider open price
                        double close = double.Parse(parts[4]); // close (adj close is highly variant and confusing)

                        dqi = new DerivativeQuoteInformation(
                            dt,
                            ltp,
                            ltp,
                            close,
                            1000,
                            1000,
                            0
                            );
                    }
                    catch { }
                }
                else if (tickFormat == TickFormatType.OnlyLTP)
                {

                    // Date,LTP
                    // 20090910:10:40:59,273.4

                    try
                    {
                        string[] parts = s.Split(',');

                        IFormatProvider culture = new CultureInfo("en-US", true);
                        DateTime dt = DateTime.ParseExact(parts[0], "yyyyMMdd:HH:mm:ss", culture);

                        double ltp = double.Parse(parts[1]);

                        dqi = new DerivativeQuoteInformation(
                            dt,
                            ltp,
                            ltp,
                            ltp,
                            1000,
                            1000,
                            0
                            );
                    }
                    catch { }
                }

            }
            catch (Exception ex)
            {
                Logger.LogException(ex);
            }

            return dqi;
        }
     }
}
